﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ANZ_AIM_GUI.Utils;
using ANZ_AIM_BLL;
using ANZ_AIM_BLL.Model;
using System.Reflection;
using System.IO;
using Outlook = Microsoft.Office.Interop.Outlook;
using log4net;
namespace ANZ_AIM_GUI
{
    public partial class frmSaleChangeMgmt : Form
    {
        //log4net
        private static readonly ILog logger = LogManager.GetLogger(typeof(frmSaleChangeMgmt));

        protected AppParam appParam = AppParam.Instance;
        bool isApprove = false;
        public frmSaleChangeMgmt(bool isApprove)
        {
            InitializeComponent();
            this.isApprove = isApprove;

            dtFromDate.Value = DateTime.Now;
            dtToDate.Value = DateTime.Now;
            //appParam.Role = User.ROLE_APPROVER;
            if (!isApprove)
            {
                this.Text = "SALE CHANGE VERIFY";
                groupBox1.Text = "Need To Verify";
                groupBox3.Visible = false;
                groupBox4.Visible = false;
                this.Size = new Size(750, 335);
            }
            else
            {
                this.Text = "SALE CHANGE APPROVE";
                groupBox3.Visible = true;
                groupBox4.Visible = true;
            }

            try
            {
                InitData();
            }
            catch (Exception ex) { throw ex; }
        }

        private void InitData()
        {
            try
            {
                string status = "";
                if (!isApprove)
                {
                    status = Constant.NEED_TO_VERIFY;
                }
                else
                {
                    status = Constant.NEED_TO_APPROVE;
                }

                BatchFileChangeUploadBLL batchFileChangeUploadBll = new BatchFileChangeUploadBLL();
                DataTable dtResult = batchFileChangeUploadBll.GetBatchFileByStatus(status);
                LoadData(dtResult);
                loadDataApproved();
                loadDataPending();
            }
            catch (Exception ex) { throw ex; }
        }

        private void LoadData(DataTable dtData)
        {
            try
            {
                dgvData.DataSource = null;
                dgvData.Columns.Clear();
                dgvData.DataSource = dtData;
                dgvData.Columns[0].HeaderText = "Batch File";
                dgvData.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvData.Columns[1].HeaderText = "File Name";
                dgvData.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dgvData.Columns[2].HeaderText = "Total Record";
                dgvData.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                dgvData.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvData.Columns[3].HeaderText = "Uploaded Date";
                dgvData.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvData.Columns[4].Visible = false;
                dgvData.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvData.Sort(dgvData.Columns[3], ListSortDirection.Descending);
                dgvData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                //add column action
                DataGridViewLinkColumn colAction = new DataGridViewLinkColumn();
                colAction.HeaderText = "Status";
                colAction.Name = "Status";

                if (!isApprove)
                {
                    colAction.Text = "Verify";
                }
                else
                {
                    colAction.Text = "Approve";
                }

                colAction.Width = 70;
                colAction.UseColumnTextForLinkValue = true;
                dgvData.Columns.Insert(5, colAction);
            }
            catch (Exception ex) { throw ex; }
        }

        private void loadDataApproved()
        {
            try
            {
                BatchFileChangeUploadBLL batchFileChangeUploadBll = new BatchFileChangeUploadBLL();
                DataTable dtResult = batchFileChangeUploadBll.GetBatchFileByStatus(Constant.APPROVED);

                dgvDataApproved.DataSource = null;
                dgvDataApproved.Columns.Clear();
                dgvDataApproved.DataSource = dtResult;
                dgvDataApproved.Columns[0].HeaderText = "Batch File";
                dgvDataApproved.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataApproved.Columns[1].HeaderText = "File Name";
                dgvDataApproved.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dgvDataApproved.Columns[2].HeaderText = "Total Record";
                dgvDataApproved.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                dgvDataApproved.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataApproved.Columns[3].HeaderText = "Uploaded Date";
                dgvDataApproved.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataApproved.Columns[4].Visible = false;
                dgvDataApproved.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataApproved.Columns[5].HeaderText = "Sent Mail";
                dgvDataApproved.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                var dgvCellStyle = new DataGridViewCellStyle();
                dgvCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgvDataApproved.Columns[5].DefaultCellStyle = dgvCellStyle;
                dgvDataApproved.Sort(dgvDataApproved.Columns[3], ListSortDirection.Descending);
                dgvDataApproved.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            }
            catch (Exception ex) { throw ex; }
        }

        private void loadDataPending()
        {
            try
            {
                BatchFileChangeUploadBLL batchFileChangeUploadBll = new BatchFileChangeUploadBLL();
                DataTable dtResult = batchFileChangeUploadBll.GetBatchFileByStatus(Constant.PENDING);

                dgvDataPending.DataSource = null;
                dgvDataPending.Columns.Clear();
                dgvDataPending.DataSource = dtResult;
                dgvDataPending.Columns[0].HeaderText = "Batch File";
                dgvDataPending.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataPending.Columns[1].HeaderText = "File Name";
                dgvDataPending.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dgvDataPending.Columns[2].HeaderText = "Total Record";
                dgvDataPending.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                dgvDataPending.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataPending.Columns[3].HeaderText = "Uploaded Date";
                dgvDataPending.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataPending.Columns[4].Visible = false;
                dgvDataPending.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDataPending.Sort(dgvDataPending.Columns[3], ListSortDirection.Descending);
                dgvDataPending.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            }
            catch (Exception ex) { throw ex; }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                string fromDate = dtFromDate.Value.ToShortDateString();
                string toDate = dtToDate.Value.AddDays(1).ToShortDateString();

                string status = "";
                if (!isApprove)
                {
                    status = Constant.NEED_TO_VERIFY;
                }
                else
                {
                    status = Constant.NEED_TO_APPROVE;
                }

                string batchFile = txtBatchFile.Text.Trim();

                BatchFileChangeUploadBLL batchFileChangeUploadBll = new BatchFileChangeUploadBLL();
                DataTable dt = batchFileChangeUploadBll.Search(status, batchFile, fromDate, toDate);

                LoadData(dt);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void dgvData_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                int selectedRowCount = dgvData.Rows.GetRowCount(DataGridViewElementStates.Selected);
                if (selectedRowCount > 0)
                {
                    DataRow dr = ((DataRowView)dgvData.SelectedRows[0].DataBoundItem).Row;
                    frmDataChangeUpload frmDateChangeUpload = new frmDataChangeUpload(dr[0].ToString());
                    frmDateChangeUpload.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void dgvDataApproved_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                int selectedRowCount = dgvDataApproved.Rows.GetRowCount(DataGridViewElementStates.Selected);
                if (selectedRowCount > 0)
                {
                    DataRow dr = ((DataRowView)dgvDataApproved.SelectedRows[0].DataBoundItem).Row;
                    frmDataChangeUpload frmDateChangeUpload = new frmDataChangeUpload(dr[0].ToString());
                    frmDateChangeUpload.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void dgvDataPending_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                int selectedRowCount = dgvDataPending.Rows.GetRowCount(DataGridViewElementStates.Selected);
                if (selectedRowCount > 0)
                {
                    DataRow dr = ((DataRowView)dgvDataPending.SelectedRows[0].DataBoundItem).Row;
                    frmDataChangeUpload frmDateChangeUpload = new frmDataChangeUpload(dr[0].ToString());
                    frmDateChangeUpload.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void dgvData_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                DataGridView dgv = sender as DataGridView;
                if (dgv.Columns[e.ColumnIndex].Name == "Status")
                {
                    string batchFileChangeID = dgvData.Rows[e.RowIndex].Cells["BatchFileChangeID"].Value.ToString();

                    if (!isApprove)
                    {
                        frmSaleChangeVerifyStatus frm = new frmSaleChangeVerifyStatus(batchFileChangeID);
                        DialogResult result = frm.ShowDialog(this);
                        if (result == DialogResult.OK)
                        {
                            InitData();
                        }
                    }
                    else
                    {
                        frmSaleChangeApproveStatus frm = new frmSaleChangeApproveStatus(batchFileChangeID);
                        DialogResult result = frm.ShowDialog(this);
                        if (result == DialogResult.OK)
                        {
                            InitData();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.InnerException == null ? ex.Message : ex.InnerException.Message, Constant.SYS_ERROR, MessageBoxButtons.OK);
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
        }

        List<int> selectedNotSentBatchFileID;
        List<int> selectedSentBatchFileID;
        private void dgvDataApproved_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                DataGridViewSelectedRowCollection selectedRowClt = dgvDataApproved.SelectedRows;
                selectedNotSentBatchFileID = new List<int>();
                selectedSentBatchFileID = new List<int>();
                foreach (DataGridViewRow row in selectedRowClt)
                {
                    if (row.Cells[5].Value.Equals("No"))
                    {
                        selectedNotSentBatchFileID.Add(int.Parse(row.Cells[0].Value.ToString()));
                    }
                    if (row.Cells[5].Value.Equals("Yes"))
                    {
                        selectedSentBatchFileID.Add(int.Parse(row.Cells[0].Value.ToString()));
                    }
                }
                dgvDataApproved.ContextMenuStrip = menuSendMail;
                menuSendMail.Show(Cursor.Position);
            }
        }




        
        private void sendMailToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<string> fileTempList = new List<string>();
            int count = 0;
            foreach (int batchFileID in selectedNotSentBatchFileID)
            {
                count++;
                DataTable employmentByBatchFileChange = new SaleInfoBLL().BuildEmploymentChanged(batchFileID.ToString());
                DataTable invertedEmployment = EmploymentByHistory(batchFileID.ToString(), employmentByBatchFileChange);
                string fileName = "Approval_" + DateTime.Now.ToString("ddMMyyyy") + string.Format(" ({0})", count) + ".xls";
                string fileTemp = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + fileName;
                NPOIHelper.ExportSaleInfoToEmploymentInfo(invertedEmployment, "EMPLOYMENT APPROVED CHANGE", fileTemp, Employment_SaleInfoFieldMappingDict());
                fileTempList.Add(fileTemp);
            }
            if (selectedSentBatchFileID.Count > 0)
            {
                DialogResult result = MessageBox.Show("Some files were already sent. Do you want to send it one more time?", "Sent files", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    foreach (int batchFileID in selectedSentBatchFileID)
                    {
                        count++;
                        DataTable employmentInforByBatchFile = new SaleInfoBLL().BuildEmploymentChanged(batchFileID.ToString());
                        DataTable invertedEmployment = EmploymentByHistory(batchFileID.ToString(), employmentInforByBatchFile);
                        string fileName = "Approval_" + DateTime.Now.ToString("ddMMyyyy") + string.Format(" ({0})", count) + ".xls";
                        string fileTemp = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + fileName;
                        NPOIHelper.ExportSaleInfoToEmploymentInfo(invertedEmployment, "EMPLOYMENT APPROVED CHANGE", fileTemp, Employment_SaleInfoFieldMappingDict());
                        fileTempList.Add(fileTemp);
                    }
                }
            }
            //Send mail
            if (count > 0)
            {
                SendEMailThroughOUTLOOK(fileTempList);
            }
            else
            {
                MessageBox.Show("Nothing to send", "No thing to send", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            loadDataApproved();
        }

        public DataTable EmploymentByHistory(string batchFileChangeId, DataTable employmentInforByBatchFile)
        {
            DataTable saleChangeById = new SaleChangeRequestBLL().GetByBatchFileChangeID(batchFileChangeId);
            foreach (DataRow dtRow in employmentInforByBatchFile.Rows)
            {

                foreach (DataRow row in saleChangeById.Rows)
                {

                    string fieldChange = row["FieldChange"].ToString();
                    string profileID = row["ProfileID"].ToString();
                    string newVAlue = row["NewValue"].ToString();

                    if (dtRow["ProfileID"].ToString().Equals(profileID))
                    {
                        string[] fieldAndNewValue = new SaleChangeRequestBLL().NewValByBatchFileProfID(batchFileChangeId, profileID, fieldChange);
                        if (fieldAndNewValue != null)
                        {
                            dtRow.SetField(fieldAndNewValue.GetValue(0).ToString(), fieldAndNewValue.GetValue(1).ToString());
                            saleChangeById.Rows.Remove(row);
                            break;
                        }
                    }



                }


            }
            return employmentInforByBatchFile;
        }

        private void SendEMailThroughOUTLOOK(List<string> fileTempList)
        {
            try
            {
                // Create the Outlook application.
                Microsoft.Office.Interop.Outlook.Application oApp = new Outlook.Application();
                oApp.ActiveWindow();
                
                    // Create a new mail item.
                Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

                // Set HTMLBody. 
                //add the body of the email
                oMsg.HTMLBody = "Content";

                //Add an attachment.
                String sDisplayName = "MyAttachment";
                int iPosition = (int)oMsg.Body.Length + 1;
                int iAttachType = (int)Outlook.OlAttachmentType.olByValue;

                //now attached the file             

                foreach (string fileTemp in fileTempList)
                {
                    var oAttach = oMsg.Attachments.Add(fileTemp, iAttachType, iPosition, sDisplayName);
                    if (File.Exists(fileTemp)) File.Delete(fileTemp);
                }



                //Subject line
                oMsg.Subject = "Employment_Approved_Change_" + DateTime.Now.ToString("ddMMyyyy") + string.Format(" {0} file(s)", fileTempList.Count); ;
                oMsg.To = "";
                oMsg.CC = "";
                oMsg.Display(true);
             
                foreach (int batchFileID in selectedNotSentBatchFileID)
                {
                    new BatchFileChangeUploadBLL().SetMailSent(batchFileID.ToString());
                }
                fileTempList.Clear();
                loadDataApproved();
            }

            catch (Exception ex)
            {
                MessageBox.Show("Error with sending proccess");
                logger.Error(ex.Message + " - " + ex.StackTrace);
            }
            finally { 
                
            }
        }



        public Dictionary<string, string> Employment_SaleInfoFieldMappingDict()
        {
            Dictionary<string, string> employment_FieldLabelDict = new Dictionary<string, string>();
            employment_FieldLabelDict.Add("ProfileID", "Profile ID");
            employment_FieldLabelDict.Add("SaleCode", "Current Sales Code");
            employment_FieldLabelDict.Add("CVCode", "Candidate Code");
            employment_FieldLabelDict.Add("EmployeeFullName", "Employee Full Name");
            employment_FieldLabelDict.Add("EmployeeFullNameE", "Employee Full Name_E");
            employment_FieldLabelDict.Add("Role", "Role");
            employment_FieldLabelDict.Add("Level", "Level");
            employment_FieldLabelDict.Add("Category", "Category");
            employment_FieldLabelDict.Add("ProductCategory", "Product Category");
            employment_FieldLabelDict.Add("Product", "Product");
            employment_FieldLabelDict.Add("TeamName", "Team Name");
            employment_FieldLabelDict.Add("TeamLeaderCode", "Team Leader Code");
            employment_FieldLabelDict.Add("Channel", "Channel");
            employment_FieldLabelDict.Add("JoiningDate", "Joining Date");
            employment_FieldLabelDict.Add("PromotionTransferDate", "PromotionTransfer Date");
            employment_FieldLabelDict.Add("Status", "Status");
            employment_FieldLabelDict.Add("ContractType", "Contract Type");
            employment_FieldLabelDict.Add("ContractTerm", "Contract Term");
            employment_FieldLabelDict.Add("ContractorName", "Contractor Name");
            employment_FieldLabelDict.Add("ContractSignDate", "Contract Sign Date");
            employment_FieldLabelDict.Add("ContractExpiryDate", "Contract Expiry Date");
            employment_FieldLabelDict.Add("BatchFileID", "Batch File ID");
            return employment_FieldLabelDict;
        }

        private void dgvDataApproved_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvDataApproved.Columns[e.ColumnIndex].HeaderText.Equals("Sent Mail"))
            {
                if (dgvDataApproved.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.Equals("No"))
                {
                    DialogResult result = MessageBox.Show("Do you want to send this file?", "Send mail", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {

                        string batchFileID = dgvDataApproved.Rows[e.RowIndex].Cells[0].Value.ToString();
                        selectedNotSentBatchFileID = new List<int>();
                        selectedNotSentBatchFileID.Add(int.Parse(batchFileID));
                        DataTable employmentInforByBatchFile = new SaleInfoBLL().BuildEmploymentChanged(batchFileID.ToString());

                        string fileName = "APPROVAL_" + DateTime.Now.ToString("ddMMyyyy") + ".xls";
                        string fileTemp = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + fileName;
                        NPOIHelper.ExportSaleInfoToEmploymentInfo(employmentInforByBatchFile, "EMPLOYMENT APPROVED CHANGE", fileTemp, Employment_SaleInfoFieldMappingDict());
                        //Send mail
                        List<string> fileTempList = new List<string>();
                        fileTempList.Add(fileTemp);
                        SendEMailThroughOUTLOOK(fileTempList);
                    }
                }
            }
        }

        private void dgvDataApproved_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewRow row in dgvDataApproved.Rows)
            {
                if (row.Cells[5].Value.Equals("No"))
                {
                    row.Cells[5] = new DataGridViewLinkCell();

                }

            }
        }

        private void txtBatchFile_TextChanged(object sender, EventArgs e)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(txtBatchFile.Text, "[^0-9]"))
            {
                //MessageBox.Show("Please enter only numbers.");
                txtBatchFile.Undo();
                txtBatchFile.ClearUndo();
            }
            else
            {
                txtBatchFile.ClearUndo();
            }
        }


    }
}
